package com.aiyige.utils.removal;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.aiyige.MyApp;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;

import java.io.File;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class ReDBHelper extends OrmLiteSqliteOpenHelper {

    /**
     * 数据库名字
     */
    private static final String DB_NAME = "aiyige.db";
    /**
     * 数据库版本
     */
//    private static int DB_VERSION = WuDaoUtils.getVersionName();
    private static int DB_VERSION = 317000;


    private static ReDBHelper instance;


    /**
     * 用来存放Dao的map
     */
    private Map<String, Dao> daos = new HashMap<String, Dao>();

    /**
     * 构造方法
     *
     * @param context
     */
    private ReDBHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    /**
     * 获取单例
     *
     * @param context
     * @return
     */
    public static synchronized ReDBHelper getHelper(Context context) {
//        context = context.getApplicationContext();
        Context appContext = MyApp.getAppContext();
        synchronized (ReDBHelper.class) {
            if (instance == null) {
                instance = new ReDBHelper(appContext);
            }
        }
        return instance;
    }

    @Override
    public void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int oldVersion,
                          int newVersion) {
    }

    /**
     * 通过类来获得指定的Dao
     */
    public synchronized Dao getDao(Class clazz) {
        Dao dao = null;
        try {
            String className = clazz.getSimpleName();
            if (daos.containsKey(className)) {
                dao = daos.get(className);
            }
            if (null == dao) {
                dao = super.getDao(clazz);
                daos.put(className, dao);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return dao;
    }

    /**
     * 释放资源
     */
    @Override
    public void close() {
        super.close();
        for (String key : daos.keySet()) {
            Dao dao = daos.get(key);
            dao = null;
        }
    }


    private boolean fileExist(String path) {
        if (TextUtils.isEmpty(path)) {
            return false;
        }
        File file = new File(path);
        return file.exists();
    }
}
